package com.example.book_libapp;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import com.example.database.library.DatabaseHandler;
import com.example.database.library.UserFunctions;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Passforg extends Activity implements OnClickListener {
		
	 	private EditText edEmail;
		private Button btnforpass;
	
		// JSON Response node names
		private static String KEY_SUCCESS = "success";
		private static String KEY_ERROR = "error";
		private static String KEY_ERROR_MSG = "error_msg";
		private static String KEY_UID = "uid";
		private static String KEY_NAME = "name";
		private static String KEY_EMAIL = "email";
		private static String KEY_CREATED_AT = "created_at";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.passforg);
		edEmail = (EditText)findViewById(R.id.forgEditEmail);
		btnforpass = (Button)findViewById(R.id.BtnRegister);
		btnforpass.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		String Email = edEmail.getText().toString();
		UserFunctions userFunction = new UserFunctions();
		JSONObject json = userFunction.forgotPassword(Email);
		// check for forgot password response
		try {
			if (json.getString(KEY_SUCCESS) != null) {

				String res = json.getString(KEY_SUCCESS); 
				if(Integer.parseInt(res) == 1){
//					 user successfully registred
//					 Store user details in SQLite Database
					DatabaseHandler db = new DatabaseHandler(getApplicationContext());
					JSONObject json_user = json.getJSONObject("user");
					
					// Clear all previous data in database
					userFunction.logoutUser(getApplicationContext());
					db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));						
					// Launch Dashboard Screen
					Intent i = new Intent(getApplicationContext(), ListViewBookActivity.class);
					// Close all views before launching Dashboard
//					dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
					// Close Registration Screen
					finish();
				}else{
					// Error in registration
//					passwordforgot.setText("Та систем бүртгүүлээгүй байна.");
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

}
